import { MissTargetError } from './../filter/missTarget.filter';
import { Middleware, IMiddleware } from '@midwayjs/core';
import { NextFunction, Context } from '@midwayjs/koa';

@Middleware()
export class DecMiddleware implements IMiddleware<Context, NextFunction> {
  resolve() {
    return async (ctx: Context, next: NextFunction) => {
      // ctx.request.setAttribute()
      ctx.setAttr('username', 'zhangsan');
      ctx.setAttr('password', '11');
      //   ctx.headers.authorization = 'wangwu';
      console.log('***********');
      const result = await next();
      console.log('***********');
      return result;
    };
  }
}

@Middleware()
export class InterceptorMiddleware
  implements IMiddleware<Context, NextFunction>
{
  // 身份认证 权限拦截
  resolve() {
    return async (ctx: Context, next: NextFunction) => {
      if (!ctx.headers.authorization) {
        throw new MissTargetError('拦截无身份 半途返回');
        // ctx.status = 888;
        // ctx.body = {
        //   msg: '拦截无身份 半途返回',
        // };
        // return;
      }
      console.log('拥有身份信息： ' + ctx.headers.authorization);
      //   有身份就放行
      const result = await next();
      return result;
      //   return undefined;
    };
  }
}
@Middleware()
export class LoginMiddleware implements IMiddleware<Context, NextFunction> {
  resolve() {
    return async (ctx: Context, next: NextFunction) => {
      // @Post("/login") {username:"zhangsan", password:"1111"}
      if (ctx.path === '/login' && ctx.method.toLowerCase() === 'post') {
        // @body() b
        const b: any = ctx.request.body;
        console.log('绑定@body', b);
        console.log(
          '去数据库根据b.username查找数据库里的密码2 对比b.password密码1 看二者是否相同'
        );
        const result = b.username === b.password;
        if (result) {
          ctx.status = 200;
          ctx.body = {
            authrization: 'nice0010200939' + b.username,
          };
        } else {
          ctx.status = 700;
          ctx.body = {
            msg: '用户名密码不匹配',
          };
        }
        return;
      } else {
        const result = await next();
        return result;
      }
    };
  }
}
